package cc.shacocloud.mirage.starter;

import cc.shacocloud.mirage.context.restful.MirageRestfulConfiguration;
import cc.shacocloud.mirage.context.restful.MirageWebServerOptions;
import cc.shacocloud.mirage.utils.FutureUtils;
import io.vertx.core.DeploymentOptions;
import io.vertx.core.Future;
import io.vertx.core.Vertx;
import io.vertx.core.http.HttpServerOptions;
import lombok.extern.slf4j.Slf4j;

/**
 * mirage web 服务应用上下文
 *
 * @author shaco
 */
@Slf4j
public class MirageRestfulApplicationContext extends MirageApplicationContext {
    
    public MirageRestfulApplicationContext() {
    }
    
    public MirageRestfulApplicationContext(ClassLoader classLoader) {
        super(classLoader);
    }
    
    @Override
    protected void finishStart() {
        super.finishStart();
        
        FutureUtils.await(deployWebVerticle());
    }
    
    /**
     * 部署 web 站点
     */
    protected Future<Void> deployWebVerticle() {
        Vertx vertx = getBean(Vertx.class);
        
        // 获取配置参数
        MirageWebServerOptions webServerOptions = getBean(MirageWebServerOptions.class);
        DeploymentOptions deploymentOptions = webServerOptions.getDeploymentOptions();
        
        // 部署站点
        // 在vertx的站点部署中默认使用该值作为前缀。
        // 站点名称拼接方式 {@code getApplicationName} + ":" + {@link Class#getCanonicalName()}
        return vertx.deployVerticle(getApplicationName() + ":" + MirageRestfulConfiguration.MIRAGE_WEB_SERVER_VERTICLE_BEAN_NAME,
                        deploymentOptions)
                .compose(deploymentId -> {
                    
                    if (log.isInfoEnabled()) {
                        HttpServerOptions serverOptions = webServerOptions.getServerOptions();
                        log.info("Mirage Restful 启动成功，实例数量：" + deploymentOptions.getInstances() + "，绑定端口：" + serverOptions.getPort());
                    }
                    
                    return Future.succeededFuture();
                });
    }
    
}
